package com.hmkj.core.service.operate.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.utils.DateUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.operate.QuestionsMapper;
import com.hmkj.core.po.operate.Questions;
import com.hmkj.core.service.operate.QuestionsService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客服提问业务相关Service接口实现<br>
 *
 * @ClassName: QuestionsServiceImpl
 * @author bin
 * @date   2017-11-30 03:04:53
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class QuestionsServiceImpl implements QuestionsService {

	@Resource
    private QuestionsMapper questionsMapper;

    @Override
    public GenericMapper<Questions,Integer> _getMapper() {
        return questionsMapper;
    }

    @Override
    public void replayQuestion(Integer id, String answer, Integer adminId) throws Exception{
        Questions questions  = questionsMapper.selectByPrimaryKey(id);
        if (null==questions){
            throw new BussinessException("问题不存在");
        }
        if(questions.getStatus() == Questions.STATUS.T2.code){
            throw new BussinessException("问题已回复");
        }
        //计算回复用时
       Date replayTime  =  new Date();
       int replyCost = DateUtils.millisecondBetween(questions.getCreateTime(),replayTime);
        questionsMapper.updateByPrimaryKeySelective(new Questions( q->{
            q.setId(id);
            q.setStatus(Questions.STATUS.T2.code);
            q.setAnswer(answer);
            q.setAdminId(adminId);
            q.setUpdateTime(replayTime);
            q.setReplayTime(replayTime);
            q.setReplyCost(replyCost);
        }));
    }

    @Override
    public List<Questions> selectListByIds(String[] ids,Integer userId) {
        Map<String, Object> param = new HashMap<>();
        String  idStr = "";
        for(int i = 0; i < ids.length; i++){
             String id  = ids[i];
            idStr += id+",";
        }
        idStr = idStr.substring(0,idStr.length()-1);
        param.put("idStr",idStr);
        param.put("status",Questions.STATUS.T2.code);
        param.put("userId",userId);
        return questionsMapper.selectListByIds(param);
    }

    @Override
    public List<Questions> selectListByQuestions(Questions questions) {
        Map<String, Object> param = new HashMap<>();
        param.put("question",questions.getQuestion());
        param.put("userId",questions.getUserId());
        return questionsMapper.selectListByQuestions(param);
    }

}
